home *** CD-ROM | disk | FTP | other *** search
- Path: news.nask.org.pl!usenet
- From: piotrpar@blue.maloka.waw.pl (Piotr Parlewicz)
- Newsgroups: comp.lang.c++
- Subject: Re: Can somebody explain me how to do this in C++
- Date: Tue, 09 Apr 1996 18:45:40 GMT
- Organization: Research and Academic Computer Network
- Message-ID: <4keb0h$d5e@bilbo.nask.org.pl>
- References: <4hkb2o$ko3@mo6.rc.tudelft.nl>
- NNTP-Posting-Host: s114.maloka.waw.pl
- X-Newsreader: Forte Free Agent 1.0.82
-
- Ejo Schrama <schrama@geo.tudelft.nl> wrote:
-
- >Suppose you've got a base class containing protected data and several
- >public methods among which there are some virtual ones. This base class
- >is inhereted to "lets call them" subclasses in which the virtual methods
- >are implemented. All subclasses are defined during the initialization of a
- >problem, however during the execution of a program "where all work is
- >executed" you only want to deal with a linked list of base class objects
- >which are accessed via a while loop. The code looks as follows:
-
- [...]
-
- >Any attempt I do to declare
-
- > Cparam_inhereted_method *localpointer2 = localpointer;
-
- >will always fail since:
- [...]
-
-
- >so that I can never execute
-
- > localpointer2->execute_routine();
-
- >The only alternative seems to introduce execute_routine to the Cparam
- >base class (which I would like to avoid). How can I avoid this?
-
- Hi, if I understood your intentions correctly, it seems that all your
- code was missing was an explicit type cast to the derived type.
- Here is a working (BC4.51) example:
-
-
- #include <stdio.h>
-
- class CBase {
- protected:
- char d ;
- public:
- void m1( ) {
- printf("m1 in base\n") ;
- }
-
- virtual void m2( ) {
- printf("m2 in base\n");
- }
- } ;
-
- class CDer : CBase {
- protected:
- char e;
- public:
- void m3( ) {
- printf("M3 in Derived\n");
- }
-
- void m2() {
- printf("M2 in Derived...\n");
- }
-
- };
-
-
-
- int main( int argc, char **argv ) {
-
- class CDer cd ; // cd will be object of derived type
- CBase *cb = (CBase*)&cd ; // cb will be generic base class pointer
- CDer *cdp = (CDer *)cb ; // now do your cast to more complex (derived)
- type
- cdp->m2(); // check if virtual function knows we are really of derived
- type
- cdp->m3(); // check if function existing only in derived works
- }
-
-
- Hope this helps
-
- Piotr Parlewicz
-
-
-